#include "mainwindow.h"
#include <QApplication>
#include "ui_mainwindow.h"
#include <QDateTime>
#include "sendfile.h"
#include "p2p.h"
#include "information.h"


Mainwindow::Mainwindow(QString name,QWidget *parent) :
	QDialog(parent),
	ui(new Ui::Mainwindow) {
	ui->setupUi(this);
	socket = new QTcpSocket();
	server = new QTcpServer();
    this->setWindowTitle(name);
	CIP = getIP();
    qDebug()<<CIP;
	QTime current_time = QTime::currentTime();
	int second = current_time.second(); //系统当前秒数
	qsrand(second);
	Cport = QString::number(qrand() % 1024 + 6000);
	CPort = Cport.toInt();//通过即时的秒来确定Port
    server->listen(QHostAddress::Any, CPort); //监听本机的某个端口
	qDebug() << CPort;



    connect(server, SIGNAL(newConnection()), this, SLOT(Connect())); //接受来自其他客户端的信号并连
    connect(socket, SIGNAL(readyRead()), this, SLOT(Read_Data())); //接受来自服务器的数据
	connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
	        this, SLOT(displayError(QAbstractSocket::SocketError)));  //发生错误时执行displayError函数
    //QString tittle = windowTitle();

    qDebug() << this->windowTitle();
    QString title = windowTitle();
    socket->abort();   //取消已有的连接
    //连接服务器
    socket->connectToHost(IP, port);
    //等待连接成功
    if (!socket->waitForConnected(30000)) {
        qDebug() << "Connection failed!";
        return;
    } else {
        qDebug() << "Connect successfully!";
    }

    QString es = "e";
    QString data = es + "#" + title + "#" + CIP + "#" + Cport;
    qDebug() << data;
    socket->write(data.toUtf8());

}
int Mainwindow::CPort = CPort;

Mainwindow::~Mainwindow() {
	delete ui;
	delete this->socket;
}

void Mainwindow::Connect() { //连接客户端
    qDebug()<<"SLOT(Connect())";
	socket = server->nextPendingConnection();
	connect(socket, SIGNAL(readyRead()), this, SLOT(Read_Data())); //获取来自服务器的数据
}


QString Mainwindow::getIP() {
	QString localHostName = QHostInfo::localHostName();//本机用户名
	QString IP;
	QHostInfo info = QHostInfo::fromName(localHostName);
    foreach (QHostAddress address, info.addresses()) {
        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
             if (address.toString().contains("fe")){
                 continue;
             }
			IP = address.toString();//本机ip地址
            qDebug()<<IP + "     IP地址";
			return IP;
		}
	}
	return NULL;
}

void Mainwindow::closeEvent(QCloseEvent *event) {//在关闭的时候自动退出登陆
	QString title = windowTitle();
	socket->abort();   //取消已有的连接
	socket->connectToHost(IP, port); //连接服务器
	socket->waitForConnected();
	QString ds = "d";
	QString data = ds + "#" + title;
	socket->write(data.toUtf8());
	close();
}

void Mainwindow::Read_Data() {
	qDebug() << "到达读取数据";
	QString data = socket->readAll();   //读取服务器发送的数据
	QStringList list = data.split("#");
	QString title = windowTitle();
	qDebug() << data;
	if (list[0] == "e") { //加载用户列表
        ui->scrollArea->setWidgetResizable(true);

        QWidget* list_widget = ui->scrollArea->takeWidget();
        QList <MyLabel*> label_list;
        for (int i = 1; i < list.length()/3; i++) {
            if (list[i] != "end") {
                QString str1 = list[(i-1)*3+1];
                QString str2 = list[(i-1)*3+2];
                QString str3 = list[(i-1)*3+3];

                label_list.append(new MyLabel());
                label_list.at(i-1)->setLabel(str1, str2.toInt());
                //label_list.at(i-1)->setStatus(str2.toInt());
                label_list.at(i-1)->setPhoto(str3.toInt());
                label_list.at(i-1)->setParent(list_widget);
                label_list.at(i-1)->setGeometry(0,67*(i-1),180,65);

                list_widget->setMinimumHeight(65*i);

                connect(label_list.at(i-1),SIGNAL(sig_DoubleClick(QString)),
                       this,SLOT(slot_MylabelDoubleClicked(QString)));

            } else ui->textBrowser->append(list[++i]);
        }
        ui->scrollArea->setWidget(list_widget);

	} else if (list[0] == "f") { //群发消息功能实现
		qDebug() << "群聊      回到客户端";
		if (list[1] != title) {
			QDateTime time = QDateTime::currentDateTime();
			QString Time = time.toString("yyyy-MM-dd ddd hh:mm:ss ");
			ui->textBrowser->append(Time);
			ui->textBrowser->append(list[1] + " : " + list[2]);
		}
    } else if (list[0] == "g") { //私聊 //本机打开的界面
        qDebug() << "私聊      客户端";
        if (list[2] == "1") {

            P2P *p2 = new P2P(Name.toLocal8Bit(),title,'g');
            p2->setWindowTitle(Name);
            p2->show();
            socket->abort();   //取消已有的连接
            YIP = list[3];
            cport = list[4].toInt();
            socket->connectToHost(YIP, cport); //连接到客户端B
            socket->waitForConnected();//等待连接
            p = 1;
            QString ms = "z";
            QString data = ms + "#" + this->windowTitle() ;
            socket->write(data.toUtf8());
        } else if (list[2] == "0") {
            p = 2;
            QMessageBox::information(this, "信息提示", "该用户不在线，您在输入框中直接输入就可以向他发送离线消息!", QMessageBox::Ok);
        }
    } else if (list[0] == 'z') {//开启P2P
        qDebug() << "到达开启P2P";
        P2P *p3 = new P2P(list[1].toLocal8Bit(),this->windowTitle(),'z');
        p3->setWindowTitle(list[1]);
        p3->show();
    } else if (list[0] == "h" && list[1] == "true") {
        QString str3 = list[4];
        int num =str3.toInt();
        if (num == 0) {
            ui->pushButton->setStyleSheet("QPushButton{border-image: url(://icon/handsomeboy.jpg);border-radius:25px;}");
        }
        if (num == 1) {
            ui->pushButton->setStyleSheet("QPushButton{border-image: url(://icon/redhair.jpg);border-radius:25px;}");
        }
        if (num == 2) {
            ui->pushButton->setStyleSheet("QPushButton{border-image: url(://icon/bearded.jpg);border-radius:25px;}");
        }
        if (num == 3) {
            ui->pushButton->setStyleSheet("QPushButton{border-image: url(://icon/bluedog.jpg);border-radius:25px;}");
        }
        if (num == 4) {
            ui->pushButton->setStyleSheet("QPushButton{border-image: url(://icon/baldman.jpg);border-radius:25px;}");
        }
        if (num == 5) {
            ui->pushButton->setStyleSheet("QPushButton{border-image: url(://icon/goddess.jpg);border-radius:25px;}");
        }
        if (num == 6) {
            ui->pushButton->setStyleSheet("QPushButton{border-image: url(://icon/greenQQ.png);border-radius:25px;}");
        }
        if (num == 7) {
            ui->pushButton->setStyleSheet("QPushButton{border-image: url(://icon/huanqian.jpg);border-radius:25px;}");
        }
        if (num == 8) {
            ui->pushButton->setStyleSheet("QPushButton{border-image: url(://icon/ourfaith.jpg);border-radius:25px;}");
        }
    }else return;
}

void Mainwindow::slot_MylabelDoubleClicked(QString str) {//双击开启P2P
    qDebug() << "双击666";
    QStringList list = str.split("\n");
    Name = list[0];
    socket->abort();
    //连接服务器
    socket->connectToHost(IP, port);
    socket->waitForConnected();
    QString gs = "g";
    QString data = gs + "#" + Name;
    socket->write(data.toUtf8());
}

//void Mainwindow::Connect_for_userlist() {//得到用户列表，点击左上角，稍微偏右一些，多点几次就点到了
//    qDebug() << this->windowTitle();
//    QString title = windowTitle();
//    socket->abort();   //取消已有的连接
//    //连接服务器
//    socket->connectToHost(IP, port);
//    //等待连接成功
//    if (!socket->waitForConnected(30000)) {
//        qDebug() << "Connection failed!";
//        return;
//    } else {
//        qDebug() << "Connect successfully!";
//    }

//    QString es = "e";
//    QString data = es + "#" + title + "#" + CIP + "#" + Cport;
//    socket->write(data.toUtf8());
//}

void Mainwindow::on_pushButton_Send_clicked() {
	QString title = windowTitle();
	QString fs;
	QString msg = ui->textEdit->toPlainText();

	if (p != 2) { //群聊
		socket->abort();   //取消已有的连接
		//连接服务器
		socket->connectToHost(IP, port);
		//等待连接成功
		if (!socket->waitForConnected(30000)) {
			qDebug() << "Connection failed!";
			return;
		} else
			qDebug() << "Connect successfully!     连接服务器";
		fs = "f"; //群聊
		QString data = fs + "#" + title + "#" + msg;
		socket->write(data.toUtf8());
	} else { //离线消息
		socket->abort();  //取消已有的连接
		//连接服务器
		socket->connectToHost(IP, port);
		//等待连接成功
		if (!socket->waitForConnected(30000)) {
			qDebug() << "Connection failed!";
			return;
		} else
			qDebug() << "Connect successfully!";
		fs = "i"; //离线消息
		QString data = fs + "#" + title + "#" + Name + "#" + msg;
		socket->write(data.toUtf8());
	}

	QDateTime time = QDateTime::currentDateTime();
	QString Time = time.toString("yyyy-MM-dd ddd hh:mm:ss ");
	ui->textBrowser->append(Time);
	ui->textBrowser->append(title + " : " + msg);
	ui->textEdit->clear();
}


void Mainwindow::on_pushButton_Connect_clicked() {//得到用户列表，点击左上角，稍微偏右一些，多点几次就点到了
	qDebug() << this->windowTitle();
	QString title = windowTitle();
	socket->abort();   //取消已有的连接
	//连接服务器
	socket->connectToHost(IP, port);
	//等待连接成功
	if (!socket->waitForConnected(30000)) {
		qDebug() << "Connection failed!";
		return;
	} else {
		qDebug() << "Connect successfully!";
	}

	QString es = "e";
	QString data = es + "#" + title + "#" + CIP + "#" + Cport;
    qDebug() << data;
	socket->write(data.toUtf8());
}

void Mainwindow::on_pushButton_clicked()
{
    Information *myinformation= new Information;
    myinformation->setWindowTitle(this->windowTitle());
    myinformation->show();
}

void Mainwindow::on_pushButton_2_clicked()
{
    socket->abort();   //取消已有的连接
    socket->connectToHost(IP, port); //连接服务器
    socket->waitForConnected();
    QString string = this->windowTitle();//用户名
    QString hs = "h";
    QString data = hs + "#" + string;
    socket->write(data.toUtf8());
}
